package com.bzyd.cloud.filters;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义全局鉴权过滤器，需要实现GlobalFilter、Ordered接口，
 * 其中GlobalFilter是gateway中的接口，Ordered是spring中的接口，控制spring初始化bean顺序
 * Created by Xianyue Dang on 2021/8/18
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    //用户登录鉴权判断
    //校验所有请求的请求参数中是否包含“token”，如果不包含则不转发路由，否则执行正常的逻辑
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (!StringUtils.equals(token, "admin")) {
            System.out.println("鉴权失败！");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        //调用chain.filter继续向下执行
        return chain.filter(exchange);
    }


    //顺序，数值越小，优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
